package net.liteheaven.xblib.plugin;

import android.content.res.AssetManager;
import android.text.TextUtils;

import java.lang.reflect.Method;

/**
 * 插件类
 *
 * Created by LiangYu on 16/8/29
 */
public class XPlugin {

    private ClassLoader classLoader;
    private String activityName;
    private String apkPath;

    private XPlugin(Builder builder){
        classLoader = builder.classLoader;
        activityName = builder.activityName;
        apkPath = builder.apkPath;
    }

    public IXActivityImpl getController(XProxyActivity activity){
        IXActivityImpl result = null;
        try {
            XProxyActivity instance = (XProxyActivity)classLoader.loadClass(activityName).newInstance();
            Method getController = instance.getClass().getMethod("getController", XProxyActivity.class);
            result = (IXActivityImpl)getController.invoke(instance, activity);
        } catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }

    public AssetManager getAssetManager(AssetManager assetManager){
        // 静态加载方式使用默认的
        if (TextUtils.isEmpty(apkPath)){
            return null;
        }
        if (assetManager == null){
            return null;
        }

        try{
            Method addAssetPath = assetManager.getClass().getMethod(
                    "addAssetPath", String.class);
            addAssetPath.invoke(assetManager, apkPath);
        }catch (Exception e){
            e.printStackTrace();
        }
        return assetManager;
    }

    public static class Builder{

        private ClassLoader classLoader;
        private String activityName;
        private String apkPath;

        public Builder(){}

        public Builder setActivityName(String activityName){
            this.activityName = activityName;
            return this;
        }

        public Builder setApkPath(String apkPath){
            this.apkPath = apkPath;
            return this;
        }

        public Builder setClassLoader(ClassLoader classLoader){
            this.classLoader = classLoader;
            return this;
        }

        public XPlugin build(){
            return new XPlugin(this);
        }
    }
}
